//
//  AppDelegate.m
//  LocomotiveGuards
//
//  Created by apple on 15/11/9.
//  Copyright (c) 2015年 REDOOR. All rights reserved.
//

#import "AppDelegate.h"
#import "RegisterBaseViewController.h"
#import "LoginViewController.h"
#import "AutoLoginViewController.h"
#import "RootviewConrtoller.h"
#import "WelcomeViewController.h"
#import <BaiduMapAPI_Map/BMKMapView.h>
#import <BaiduMapAPI_Base/BMKMapManager.h>
#import "ThanksViewController.h"
#import "APService.h"
#import "IQKeyboardManager.h"
#import "testViewController.h"
#import "SecurityMessageFmdbModel.h"


@interface AppDelegate ()
{
    BMKMapManager* _mapManager;
    AFHTTPRequestOperationManager *_hTTPRequestOperationManager;

}
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
    {
        //categories
        [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                       UIUserNotificationTypeSound |
                                                       UIUserNotificationTypeAlert) categories:nil];
    }
    else
    {
        //categories nil
        [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                       UIRemoteNotificationTypeSound |
                                                       UIRemoteNotificationTypeAlert) categories:nil];
    }
#else
    //categories nil
    [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                   UIRemoteNotificationTypeSound |
                                                   UIRemoteNotificationTypeAlert) categories:nil];
#endif
    [APService setupWithOption:launchOptions];
  
    /**
     *  用户点击apn通知导致app被启动运行
     */
    
    //开启键盘自适应
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [[IQKeyboardManager sharedManager] setShouldResignOnTouchOutside:YES];
    //检测版本url是否已经获取到
    
    NSString *urlapp=[[NSUserDefaults standardUserDefaults]objectForKey:APP_URL];
    if(urlapp==nil){
        [self getVersionUrlinAppStore];
    }
    
    // Override point for customization after application launch.
    // 要使用百度地图，请先启动BaiduMapManager//百度地图注册以及使用
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    BOOL ret = [_mapManager start:@"22NNeB1acF2DBqZRjGkErQfA"  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"yiwan_confirmpwd"];
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"yiwan_pwd"];
    //判读是否启动过进入不同的页面的
    NSString *judgeNo=[[NSUserDefaults standardUserDefaults]objectForKey:@"judgeNo"];
    //judgeNo=@"0";
    if(judgeNo==nil)
    {
        
        [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"judgeNo"];
        
//        欢迎界面
        self.window.rootViewController=[WelcomeViewController new];
        
    }
    else if([judgeNo isEqualToString:@"0"]){
//        登录状态
        self.window.rootViewController=[LoginViewController new];
    }
    else{
//        自动登陆状态进行操作
        self.window.rootViewController=[AutoLoginViewController new];
    }

    [application setApplicationIconBadgeNumber:0];
    
    
    NSDictionary * remoteNotificationDict = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    
    
    
    
    
    
    if (remoteNotificationDict)
    {
        NSDictionary *aps = [remoteNotificationDict valueForKey:@"aps"];
        NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
        
        [application setApplicationIconBadgeNumber:0];
      
        
        
        if ([self.window.rootViewController isKindOfClass:[RootviewConrtoller class]])
        {
            ((RootviewConrtoller *)(self.window.rootViewController)).selectedIndex = 1;
        }
        
        NSDictionary * msgDict = @{@"msg":content,
                                   @"loginId":remoteNotificationDict[@"loginId"],
                                   @"time":remoteNotificationDict[@"time"],
                                   @"type":remoteNotificationDict[@"type"],
                                   @"bid":remoteNotificationDict[@"bid"],
                                   @"msgId":remoteNotificationDict[@"msgId"]};
        NSString * loginId = [[NSUserDefaults standardUserDefaults]objectForKey:@"phonenumber"];
        if (loginId && [loginId isEqualToString:msgDict[@"loginId"]])
        {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"remoteAPNNotification" object:nil userInfo:msgDict];
        }
    }
 
    return YES;
}

-(void)changeRootviewcontroller
{
    self.window.rootViewController=[RootviewConrtoller new];
}


//网路请求初始化模式
-(AFHTTPRequestOperationManager *)shareHTTPRequestOperationManager
{
    if (nil == _hTTPRequestOperationManager)
    {
        _hTTPRequestOperationManager = [AFHTTPRequestOperationManager manager];
    }
    
    return _hTTPRequestOperationManager;
}


//避免在复杂的多线程环境，避免出现死锁
dispatch_queue_t dispatch_create_serial_queue_for_name(const char * name)
{
    dispatch_queue_t customQueue = dispatch_queue_create(name, NULL);
    dispatch_queue_set_specific(customQueue, kQueueNameKey, (void *)(name), NULL);
    return customQueue;
}


static void *kQueueNameKey = (__bridge void *)@"kQueueNameKey";



- (AFSecurityPolicy*)customSecurityPolicy
{
    // /先导入证书
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"007userapp" ofType:@"cer"];//证书的路径
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    
    
    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = NO;
    securityPolicy.validatesCertificateChain = NO;
    
    //securityPolicy.pinnedCertificates = @[certData];
    
    return securityPolicy;
}



//web端安全验证
-(void)GenerateHTTPRequestWithUrl:(NSString *)url
                        withParam:(NSDictionary*)parameterDic
                          success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                          failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure{
    
    
    AFHTTPRequestOperationManager *manager = [self shareHTTPRequestOperationManager];
    // 设置请求格式
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    // 设置返回格式
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
   
//    安全验证返回网络错误
    
    [manager setSecurityPolicy:[self customSecurityPolicy]];
    
    NSLog(@"安全验证  %@",[self customSecurityPolicy]);
    
    
//    dispatch_queue_t requestQueue = dispatch_create_serial_queue_for_name("kRequestCompletionQueue");
//    manager.completionQueue=requestQueue;

    
    //allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    //如果是需要验证自建证书，需要设置为YES
    //securityPolicy.allowInvalidCertificates = NO;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    //securityPolicy.validatesDomainName = YES;
    
    //validatesCertificateChain 是否验证整个证书链，默认为YES
    //设置为YES，会将服务器返回的Trust Object上的证书链与本地导入的证书进行对比，这就意味着，假如你的证书链是这样的：
    //GeoTrust Global CA
    //    Google Internet Authority G2
    //        *.google.com
    //那么，除了导入*.google.com之外，还需要导入证书链上所有的CA证书（GeoTrust Global CA, Google Internet Authority G2）；
    //如是自建证书的时候，可以设置为YES，增强安全性；假如是信任的CA所签发的证书，则建议关闭该验证，因为整个证书链一一比对是完全没有必要（请查看源代码）；
    //securityPolicy.validatesCertificateChain = NO;
    
    
    
    //manager.securityPolicy=securityPolicy;
    
   //设置加载解析模式
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    //设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    [manager.requestSerializer setTimeoutInterval:K_TimeOutInterval];
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    [manager POST:url parameters:parameterDic success:success failure:failure];
    
    NSLog(@"安全验证信息  %@  %@", url,parameterDic);



}


//进行上传数据和修改数据。
- (void)UploadHTTPRequestWithUrl:(NSString *)url
                       withParam:(NSDictionary*)parameterDic
       constructingBodyWithBlock:(void (^)(id<AFMultipartFormData> formData))block
                         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure{
    
    
    
    AFHTTPRequestOperationManager *manager = [self shareHTTPRequestOperationManager];
    // 设置请求格式
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    // 设置返回格式
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    [manager.requestSerializer setTimeoutInterval:K_TimeOutInterval];
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    manager.securityPolicy.allowInvalidCertificates = YES;
    [manager POST:url parameters:parameterDic constructingBodyWithBlock:block success:success failure:failure];


}


 

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)getVersionUrlinAppStore {
    
    NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://itunes.apple.com/lookup?id=1073033811"]];
    if(data){
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];//转换数据格式
        long result=[[dic objectForKey:@"resultCount"]longValue];
        if(result ==1){
            NSArray *array=[dic objectForKey:@"results"];
            NSDictionary *dic_result=array[0];
            NSString *trackViewUrl=dic_result[@"trackViewUrl"];
            NSMutableString *app_url=[NSMutableString stringWithString:trackViewUrl];
            NSRange range;
            range.length=5;
            range.location=0;
            [app_url replaceCharactersInRange:range withString:@"itms"];
            //存储下载更新版本的URL
            [[NSUserDefaults standardUserDefaults]setObject:app_url forKey:APP_URL];
            
        }
        
    }
   

}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    // Required
    [APService registerDeviceToken:deviceToken];
    NSString * registrationId = [APService registrationID];
    NSLog(@"注册设备Token成功!  %@   %@",deviceToken,registrationId);

}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error NS_AVAILABLE_IOS(3_0)
{
    NSLog(@"注册设备Token失败！");
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
#if 0
    // Required
    [APService handleRemoteNotification:userInfo];
    NSLog(@"收到通知:%@", userInfo);
    ((RootviewConrtoller *)(self.window.rootViewController)).selectedIndex = 1;
#endif
}




//
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
    
    
    NSLog(@"推送通知的内容是 %@   %@ %@ ",content,aps,userInfo);

    
    
    [application setApplicationIconBadgeNumber:0];
    
    
     //网络数据擦偶哦 

    /**
     *  参数有效性判断,
     */
    if (!content || [content isEqualToString:@""]
        ||!userInfo[@"loginId"] || [userInfo[@"loginId"] isEqualToString:@""]
        ||!userInfo[@"time"] || [userInfo[@"time"] isEqualToString:@""]
        ||!userInfo[@"type"] || [userInfo[@"type"] isEqualToString:@""]
        ||!userInfo[@"bid"] || [userInfo[@"bid"] isEqualToString:@""]
        ||!userInfo[@"msgId"] || [userInfo[@"msgId"] isEqualToString:@""])
    {
        return;
    }
    
    NSDictionary * msgDict = @{@"msg":content,
                               @"loginId":userInfo[@"loginId"],
                               @"time":userInfo[@"time"],
                               @"type":userInfo[@"type"],
                               @"bid":userInfo[@"bid"],
                               @"msgId":userInfo[@"msgId"]};
    
  


    
//    NSString * loginId = [[NSUserDefaults standardUserDefaults]objectForKey:@"phonenumber"];
    NSString * msgId = userInfo[@"msgId"];
//    
//    if (loginId && [loginId isEqualToString:msgDict[@"loginId"]])
//    {
        /**
         *  如果指定msgId的消息存在，则忽略消息
         */
        SecurityMessageFmdbModel * msgModel = [[SecurityMessageFmdbModel alloc]init];
        if (![msgModel messageIsExist:msgId])
        {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"remoteAPNNotification" object:nil userInfo:msgDict];
            
            if ([self.window.rootViewController isKindOfClass:[RootviewConrtoller class]])
            {
                ((RootviewConrtoller *)(self.window.rootViewController)).selectedIndex = 1;
            }
        }
//    }

    [APService handleRemoteNotification:userInfo];
    NSLog(@"收到通知:%@", userInfo);
    completionHandler(UIBackgroundFetchResultNewData);
}

@end
